
#include "common.h"
#include "sock.h"

#define BUFF_MAX (1024)
u8 recv_buff[BUFF_MAX];

#define FD_MAX (1024)

#define get_idle_fds_pos(fds) \
({	\
	int i = 0;	\
	for(;i < FD_MAX;i++){	\
		if(fds[i].fd == -1)	\
			break;	\
	}	\
	(i);	\
})

int main(int argc, char **argv)
{
	signal(SIGPIPE, SIG_IGN);

	int sock_fd = get_sock("127.0.0.1",PORT);

	//定义poll的事件监听数组
    //struct pollfd {
    //   int   fd;         /* file descriptor */
    //   short events;     /* requested events */
    //   short revents;    /* returned events */
    //};

	struct pollfd fds[FD_MAX];	
	memset(fds,-1,sizeof(struct pollfd) * FD_MAX);

	//填充socket连接监听fd
	fds[0].fd = sock_fd;
	fds[0].events = POLLRDNORM;

	while(1){
		int n = poll(fds,FD_MAX,-1);
		if(n < 0){
			perror("select failed!");
			exit(EXIT_FAILURE);
		}
		printf("poll event num:%d\n", n);
		if(fds[0].revents & POLLRDNORM){
			//获取连接
			int conn_fd = get_connfd(sock_fd);
			//加入poll数组
			int index = get_idle_fds_pos(fds);
			if(index >= FD_MAX){
				perror("too many client!");
			}
			fds[index].fd = conn_fd;
			fds[index].events = POLLRDNORM;
			n--;
			printf("one client connect ok.\n");
		}

		for(int i = 1;i < FD_MAX;i++){
			if(fds[i].fd < 0) continue;
			if(fds[i].revents & (POLLERR | POLLHUP)){
				close(fds[i].fd);
				memset(&(fds[i]), -1, sizeof(struct pollfd));
				//处理完事件后跳出
				if(n-- <= 0) break;
				continue;				
			}
			if(fds[i].revents & POLLRDNORM){
				int count = read(fds[i].fd, recv_buff, BUFF_MAX);
				if(count < 0){
		            perror("read error!");
		        } 

		        recv_buff[count] = '\0';	
		        printf("recv:%s", recv_buff);        
		        count = write(fds[i].fd,"server recv done.\n",strlen("server recv done.\n"));   
		        if(count < 0){
		            perror("write error!");
		        } 	        
				//处理完事件后跳出
				if(n-- <= 0) break;
			}
		}
	}

	return 0;
}